package com.walterlife.javacore;

import java.util.SortedMap;
import java.util.TreeMap;

/**
 * ConsistentHash
 *
 * @author zhuyuwei
 * @date 2017/6/6
 */
public class ConsistentHash {
    private static String[] strings = {"192.168.1.1:1111", "192.168.1.2:1111", "192.168.1.3:111"};

    private static SortedMap<Integer, String> sortedMap = new TreeMap<>();

    static {
        for (int i = 0; i < strings.length; i++) {
            int hash = getHash(strings[i]);
            System.out.println("[" + strings[i] + "]加入集合中，其hash值为：" + hash);
            sortedMap.put(hash, strings[i]);
        }
    }

    /**
     * 使用FNV1_32_HASH算法计算服务器的Hash值,这里不使用重写hashCode的方法，最终效果没区别
     */
    private static int getHash(String str)
    {
        final int p = 16777619;
        int hash = (int)2166136261L;
        for (int i = 0; i < str.length(); i++)
            hash = (hash ^ str.charAt(i)) * p;
        hash += hash << 13;
        hash ^= hash >> 7;
        hash += hash << 3;
        hash ^= hash >> 17;
        hash += hash << 5;

        // 如果算出来的值为负数则取其绝对值
        if (hash < 0)
            hash = Math.abs(hash);
        return hash;
    }

    public static String getServer(String host) {
        int hash = getHash(host);
        return "";
    }
}
